import React from 'react';

export default class Header extends React.Component {
  state = {
    // 用户名输入框
    username: '',
    // 评论内容
    content: '',
  };

  handleChange = (e) => {
    this.setState({ [e.target.name]: e.target.value });
  };

  handleSubmit = (e) => {
    e.preventDefault();

    if (!this.state.username.trim() || !this.state.content.trim()) return alert('别乱写');
    const { username, content } = this.state;

    // 1. 将username和content传给父组件，让父组件完成新增数据功能
    this.props.handleAdd({ username, content, id: Date.now() });
  };

  render() {
    const { username, content } = this.state;
    const { handleClear } = this.props;
    return (
      <form onSubmit={this.handleSubmit}>
        <input
          className="user"
          type="text"
          placeholder="请输入评论人"
          value={username}
          name="username"
          onChange={this.handleChange}
        />
        <br />
        <textarea
          className="content"
          cols="30"
          rows="10"
          placeholder="请输入评论内容"
          value={content}
          name="content"
          onChange={this.handleChange}
        />
        <br />
        {/* 2.2 给发表按钮，绑定onClick  */}
        <button>发表评论</button>
        {/* 4.1 绑定onClick事件与handleClear */}

        <button type="button" onClick={handleClear}>
          清空评论
        </button>
      </form>
    );
  }
}
